<template>
  <el-input
    v-model="numberVal"
    v-nochinese
    v-bind="$attrs"
    size="small"
    :style="{ width }"
    @blur="handleBlurNumber"
    @change="handleChange"
  ></el-input>
</template>

<script>
export default {
  data() {
    return {
      numberVal:"",
    };
  },
  props: {
    value:{
       type:String|Number,
       default:'' 
    },
    width: {
      type: String,
      default: "100%",
    },
    min:{
        type:Number,
        default:1
    },
    max:{
        type:Number,
        default:9999
    }
  },
  watch:{
    value:{
        handler(val){
          this.numberVal = val
        },
        immediate:true,
        deep:true
    },
  },
  methods:{
    handleBlurNumber(){
      if(!this.numberVal) return
      // 使用正则表达式匹配正整数
      const regex = /^[1-9]\d*$/;
      // 如果输入的值不是正整数，则将其设置为上一个有效值
      if (!regex.test(this.numberVal)) {
        this.numberVal = this.min;
      } else {
        if (this.numberVal > this.max) {
          this.numberVal = this.max;
        }
      }
      this.handleChange()
    },

    handleChange(){
      this.$emit('input',this.numberVal)
    }
  },
};
</script>